package main

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"src/Internal"
	"src/transmissionServer"
	"strings"
	"time"
)

func main() {
	router := gin.Default()

	// GET请求，返回JSON响应
	router.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "get ping",
		})
	})

	// POST请求，上传文件
	router.POST("/upload", func(context *gin.Context) {
		// 获取单个文件
		file, err := context.FormFile("file1")
		if err != nil {
			context.JSON(http.StatusUpgradeRequired, gin.H{
				"message": err.Error(),
			})
			return
		}

		log.Println(file.Filename)
		// 生成新的文件名	//lighttpd-1.4.45.tar
		str := fmt.Sprintf("-%d.tar", time.Now().Unix())
		ReFileName := strings.Replace(file.Filename, ".tar", str, 1)
		ReFileNameAndPath := fmt.Sprintf("transmissionServer/RevFile/%s", ReFileName)
		err = context.SaveUploadedFile(file, ReFileNameAndPath) // 保存上传文件到指定的目录
		if err != nil {
			log.Println(err)
			return
		}

		// 调用transmissionServer的TransFile函数
		transmissionServer.ScpSend(ReFileName, ReFileNameAndPath) // 调用客户端工具传输文件
		index := strings.LastIndex(file.Filename, ".")
		var DirName string
		if index != -1 {
			DirName = file.Filename[:index]
		}
		context.JSON(http.StatusOK, gin.H{
			"message":    fmt.Sprintf("'%s' uploaded!", ReFileName),
			"ReFileName": ReFileName,
			"DirName":    DirName,
		})
	})

	// POST请求，运行Jenkins任务
	router.POST("/RunJenkins", func(c *gin.Context) {
		// 获取文件名
		FileName := c.PostForm("filename")
		DirName := c.PostForm("dirname")
		//fmt.Println("file name :", FileName)
		log.Printf("FileName：%s ,DirName : %s  \n", FileName, DirName)
		if FileName == "" || DirName == "" {
			c.JSON(http.StatusBadRequest, gin.H{
				"message":  fmt.Sprintf("JenkinsJob  not run successfull"),
				"filename": FileName,
				"dirname":  DirName,
			})
		}

		// 调用Internal.JenkinsToRun函数执行Jenkins任务
		buildOutput := Internal.JenkinsToRun(FileName, DirName)
		//buildOutputJson, _ := json.Marshal(buildOutput)

		log.Printf("%s send to Jenkins\n", FileName)
		c.JSON(http.StatusOK, gin.H{
			"message":     "JenkinsJob test to run is ok",
			"buildOutput": buildOutput,
		})
	})

	err := router.Run(":8088") // 监听并在 0.0.0.0:8088 上启动服务
	if err != nil {
		panic(err)
	}
}
